//
//  YAEmoticonsVC.swift
//  表情键盘[练习]
//
//  Created by 鱼龙之梦 on 15/9/12.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
private let YAEmotionCellID = "YAEmotionCellID"
class YAEmoticonsVC: UIViewController {
    var selectedEmotionCallBack:(emotion:YAEmoticon) ->()
    init(selectedEmoticon:(emoticon:YAEmoticon)->()){
        selectedEmotionCallBack = selectedEmoticon
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.redColor()
      //  viewModel.loadPackages()
        setupUI()
    }
    @objc private func cilckItem(item:UIBarButtonItem){
        let indexPath = NSIndexPath(forRow: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    private func setupUI(){
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        //注意：自动布局
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["tb":toolbar,"cv":collectionView]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: [], metrics: nil, views: viewDict))
        prepareToolbar()
        prepareCollectionView()
    }
    private func prepareCollectionView(){
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.registerClass(YAEmotionCell.self, forCellWithReuseIdentifier: YAEmotionCellID)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    private func prepareToolbar(){
        toolbar.tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
        var index = 0
        for p in viewModel.packages{
            items.append(UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self, action: "cilckItem:"))
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
    }
    //MARK:--- 工具栏
    private lazy var toolbar = UIToolbar()
     //MARK:--- cllectionView
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: YAEmoticonLayout())
    //MARK:--- 表情包的视图模型
    private lazy var viewModel = YAEmoticonViewModel.sharedEVM
}

//注意：表情键盘的布局
private class YAEmoticonLayout:UICollectionViewFlowLayout{
    private override func prepareLayout() {
        super.prepareLayout()
        //注意：算宽度
        let w = collectionView!.bounds.width / 7
        //注意：算边界
        let margin = (collectionView!.bounds.height - 3 * w) * 0.499
        
        itemSize = CGSize(width: w, height: w)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
}
extension YAEmoticonsVC:UICollectionViewDataSource,UICollectionViewDelegate{
     //MARK:--- 分组数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return viewModel.packages.count 
    }
     //MARK:--- 每个section 对应表情包中包涵的表情数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YAEmotionCellID, forIndexPath: indexPath) as! YAEmotionCell
        
        cell.emoticon = viewModel.emoticon(indexPath)
        
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        selectedEmotionCallBack(emotion: viewModel.emoticon(indexPath))
        //添加最近表情符号
        viewModel.favorite(indexPath)
    }
}
//表情cell 38
private class YAEmotionCell:UICollectionViewCell
{
    var emoticon:YAEmoticon?{
        didSet{
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState:UIControlState.Normal)
            //问题：这里的文字为什么没显示：因为这里的文字已经转化成了表情符号
            emoticonButton.setTitle(emoticon!.emoji, forState: UIControlState.Normal)
            if emoticon!.isRemove{
                print("isRemove")
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }

        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(emoticonButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var emoticonButton:UIButton = {
         let btn = UIButton()
        btn.backgroundColor = UIColor.whiteColor()
        //返回相同中心点的矩形
        btn.frame = CGRectInset(self.bounds, 4, 4)
        btn.titleLabel?.font = UIFont.systemFontOfSize(32)
        btn.userInteractionEnabled = false
        return btn
    }()
}
